﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SD.LLBLGen.Pro.ORMSupportClasses;
using CARMSData.CollectionClasses;
using CARMSData.EntityClasses;
using CARMSData.HelperClasses;

namespace CARMSBusiness
{
    public class LogBusiness
    {

        public static void AddLog(LogEntity entity)
        {
            entity.Save();
        }

        /// <summary>
        /// when session end ,then log curren user's duration while login
        /// </summary>
        /// <param name="entity"></param>
        public static void UpdateLog(string sessionID, DateTime logoutDate, string userName)
        {
            var collection = new LogCollection();
            collection.GetMulti(LogFields.SessionId == sessionID & LogFields.UserName == userName,0, new SortExpression { LogFields.LogTime | SortOperator.Descending });
            if (collection.Count > 0)
            {
                TimeSpan timeSpan = logoutDate - collection[0].LogTime;
                var dureation = timeSpan.TotalMinutes;
                collection[0].LogOutTime = logoutDate;
                collection[0].Duration =Convert.ToDecimal(dureation);
                collection[0].Save();
            }
        }


        public static bool DeleteLog(int logID)
        {
            var entity = new LogEntity(logID);
            if (!entity.IsNew)
            {
                return entity.Delete();
            }
            return false;
        }



        public static int BulkDelete(PredicateExpression condition)
        {
            var collection = new LogCollection();
            return collection.DeleteMulti(condition);
        }

        public static LogCollection GetLogList()
        {
            var collection = new LogCollection();
            collection.GetMulti(null, 0, new SortExpression { LogFields.LogTime | SortOperator.Descending });
            return collection;
        }


        public static LogCollection GetLogList(PredicateExpression Condition, SortExpression sort, int pageSize, int pageIndex)
        {
            var collection = new LogCollection(); 
            collection.GetMulti(Condition, 0, sort, null, pageIndex, pageSize);
            return collection;
        }


        public static List<string> GetLogCategories()
        {
            var collection = new LogCollection();
            collection.GetMulti(null);
            var list = from entity in collection
                       group entity by entity.Category
                           into newEntity
                           select newEntity.Key;

            return list.ToList();
        }

        public static LogEntity GetLogData(int logID)
        {
            var entity = new LogEntity(logID);
            if (!entity.IsNew)
            {
                return entity;
            }
            return null;
        }


    }
}
